package com.github.wxiaoqi.security.common.exception;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.github.wxiaoqi.security.common.util.ResponseHelper;

/** 
* @author: bolei
* @date：2018年8月24日 下午12:37:59 
* @description：处理全局异常
*/

@RestControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    Map<String, Object> handleException(Exception e){
        LOGGER.error(e.getMessage(), e);
        return ResponseHelper.failure("500", e.getMessage());
    }

    /**
     * 处理所有业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    Map<String, Object> handleBusinessException(BusinessException e){
        LOGGER.error(e.getMessage(), e);
        return ResponseHelper.failure("500", e.getMessage());
    }

    /**
     * 处理所有接口数据验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        LOGGER.error(e.getMessage(), e);
        return ResponseHelper.failure("500", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}
